<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   ref="refHiGroup" :search-form="searchItems" :create-label="hasAdd() ? '新增分组' : ''"
                   :add-item="addGroup" />
    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
    <LevelSelectorDialog ref="refLevelDlg" :load="onLoadMoveGroup" :title="title" :tag="'分组'"
                         :root-item="{id:'',name:'分组列表'}" mode="MOVE" :level-mode="true" :finish-select="onFinishMove" />

  </div>
</template>

<script setup lang="ts">

import {computed, onMounted, reactive, ref} from "vue";
import HierarchyList from "@/views/sop/list/HierarchyList.vue";
import {groupSearchForms} from "@/views/sop/data/PageData";
import EditDialog from "@/components/common/EditDialog.vue";
import {msgError, msgInfo, showInfo} from "@/utils/InfoUtil";
import LevelSelectorDialog from "@/views/sop/selector/LevelSelectorDialog.vue";
import {useCurrent} from "@/utils/sop/UseCurrentFunc";
import {useAssetOp} from "@/utils/sop/UseAssetOp";
import {SERVERS, TYPES} from "@/stores/conf";
import {useTerminal} from "@/utils/sop/UseTerminal";
import {getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";
import {buildAsset} from "@/utils/sop/DataUtil";
import {hasPermit} from "@/utils/sop/PermitUtil";

const props = withDefaults(defineProps<{
  entry: any,
  hasLevel?: boolean,
  product?: boolean,
  fromDetail?: boolean,
  loadGroup?: any,
  saveGroup?: any,
  deleteGroup?: any,
  moveGroup?: any,
  loadMoveGroup?: any,
  clickCurrent?: any,
  setRefreshRoot?: any,
}>(), {
  hasLevel: true,
});

const refHiGroup = ref();
const refEditDlg = ref();
const refLevelDlg = ref();

const currentItem = ref();
const {onTerminal} = useTerminal(props.entry.name);
const searchItems = ref(groupSearchForms({
  show: props.product,
  onChanged: onTerminal,
}));

const {updateCurrent, current} = useCurrent(props.entry.name);
const {doLoadAsset, doSaveAsset, doDeleteAsset, doMoveAsset, doLoadMoveAsset} = useAssetOp(props.entry);

const title = computed(() => {
  return `移动 ${currentItem.value?.name || '分组'}`;
})

const hasAdd = () => {
  if (SERVERS.REALM == props.entry.server) {
    return hasPermit('realm:group:add');
  } else {
    return hasPermit('platform:group:add');
  }
}

const hasEdit = () => {
  if (SERVERS.REALM == props.entry.server) {
    return hasPermit('realm:group:edit');
  } else {
    return hasPermit('platform:group:edit');
  }
}

const hasDelete = () => {
  if (SERVERS.REALM == props.entry.server) {
    return hasPermit('realm:group:delete');
  } else {
    return hasPermit('platform:group:delete');
  }
}

const hasMove = () => {
  if (SERVERS.REALM == props.entry.server) {
    return hasPermit('realm:group:move');
  } else {
    return hasPermit('platform:group:move');
  }
}

const getTargetId = () => {
  return '';
}

const rules = reactive({
  name: [{required: true, message: '请输入分组名称', trigger: ['blur']}],
})

const refresh = async () => {
  await refHiGroup.value?.refresh()
}

const onSubmit = async (item: Record<string, any>) => {
  let result;
  let assetInfo = buildAsset(item, 'GROUP', {
    comment: item.comment || '',
  });

  assetInfo.classify = "GROUP_TREE";

  if (props.saveGroup) {
    result = await props.saveGroup(assetInfo);
  } else {
    result = await doSaveAsset(getTargetId(), assetInfo);
  }

  if (result && result.code === 0) {
    msgInfo('保存分组信息成功!');
    await refresh();
  } else {
    msgError(result ? result.message : '保存分组信息失败！');
  }

  return result;
}

const loadData = async (params: any) => {
  let result;
  const id: string = current().id;

  if (props.fromDetail && !id) {
    return result;
  }
  if (!props.fromDetail && id) {
    return result;
  }

  const p: any = {
    parentId: id,
    ...params,
  };

  if (props.loadGroup) {
    result = await props.loadGroup(p);
  } else {
    result = await doLoadAsset(getTargetId(), TYPES.GROUP, p)
  }

  if (result && result.code === 0) {
    handleResult(result.data || [], ['comment']);
    msgInfo('加载分组信息成功!');
  } else {
    msgError(result ? result.message : '加载分组信息失败！');
  }

  return result;
}

const onFinishMove = async (item: any) => {
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.GROUP,
    parentId: item.id,
  };

  if (props.moveGroup) {
    await props.moveGroup(p);
  } else {
    await doMoveAsset(getTargetId(), p);
  }

  await refresh();

  if (props.setRefreshRoot && !item.id) {
    props.setRefreshRoot();
  }
}

/**
 * 移动到顶层
 */
const onMoveToTop = async () => {
  await onFinishMove({id: ''});
}

const onLoadMoveGroup = async (params: any) => {
  let result: any;
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.GROUP,
    ...params,
  };

  if (props.loadMoveGroup) {
    result = await props.loadMoveGroup(p);
  } else {
    result = await doLoadMoveAsset(getTargetId(), p);
  }

  return result;
}

const handleDeleteGroup = async (item: any) => {
  if (props.deleteGroup) {
    return await props.deleteGroup(item);
  } else {
    return await doDeleteAsset(getTargetId(), item);
  }
}

const newGroup = () => {
  return {
    state: 1,
    type: TYPES.GROUP,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const buildGroupOperations = (row: any) => {
  const operations: any = [];
  if (props.hasLevel) {
    operations.push({
      name: '新增',
      disabled: (row: any) => {
        return !hasAdd();
      },
      callback: (data: any, row: any, index: number) => {
        const parent = row;

        currentItem.value = newGroup();
        currentItem.value.disabled = true;
        currentItem.value.parentId = parent.id;
        currentItem.value.treeData = [
          {
            value: parent.id,
            label: parent.name,
          }
        ]
        refEditDlg.value?.editAdd('新增子分组', currentItem.value);
      }
    });
  }
  operations.push({
    name: '编辑',
    iconType: 'primary',
    disabled: (row: any) => {
      return !hasEdit();
    },
    callback: (data: any, row: any, index: number) => {
      currentItem.value = row;
      refEditDlg.value?.editUpdate('编辑分组', row);
    }
  });

  if (props.hasLevel) {
    operations.push({
      name: '移动',
      iconType: 'primary',
      disabled: (row: any) => {
        return !hasMove();
      },
      callback: (data: any, row: any) => {
        currentItem.value = row;
        refLevelDlg.value.select(title.value);
      }
    });
    operations.push({
      name: '移到顶层',
      iconType: 'primary',
      disabled: (row: any) => {
        return !hasMove();
      },
      callback: (data: any, row: any) => {
        currentItem.value = row;
        onMoveToTop();
      }
    });
  }

  operations.push({
    type: 'confirm',
    name: '删除',
    disabled: (row: any) => {
      return !hasDelete();
    },
    confirm: async (data: any, row: any) => {
      if (row.children && row.children.length != 0) {
        showInfo('请先删除分组子分组！');
      } else {
        const result: any = await handleDeleteGroup(row);
        if (result && result.code == 0) {
          msgInfo('删除用户分组成功！');
          await refresh();
        } else {
          msgError(result?.message || '删除用户分组失败！');
        }
      }
    },
    cancel: () => {
    }
  });

  return operations;
}

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'parentId',
    name: '父分组',
    hideCol: true,
    type: 'tree',
    readOnly: true,
    treeKey: 'parentName',
    canEdit: false,
  },
  {
    id: 'name',
    name: '分组名称',
    show: true,
    action: (data: any, row: any) => {
      updateCurrent({type: TYPES.GROUP, ...row})
    }
  },
  {
    id: 'code',
    name: '分组编码',
    show: true,
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return getStateTag(tag); },
    tagText: (tag: number) => { return getStateText(tag); },
    options: getStateOptions()
  },
  {
    id: 'comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    buildOperations: (row: any) => {
      return buildGroupOperations(row);
    },
  }
]);

const addGroup = () => {
  currentItem.value = newGroup();
  currentItem.value.parentId = current().id;
  refEditDlg.value?.editAdd('新增分组', currentItem.value);
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
